<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.ProcessCalibTask"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
    >
      <el-divider class="el-divider-specail" content-position="left"
        ><span>{{ dataList.EquipInfo }}</span>
      </el-divider>
      <el-table
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
        height="130px"
      >
        >
        <el-table-column :label="dataList.DeviceNumber">
          <template slot-scope="scope">
            {{ scope.row.num }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        >
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceSpecifications">
          <template slot-scope="scope">
            {{ scope.row.specifications }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceFactoryNum">
          <template slot-scope="scope">
            {{ scope.row.factoryNum }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceStatus">
          <template slot-scope="scope">
            {{ scope.row.statusName }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en'
              ? dataList.eDeviceStorageAddress
              : dataList.DeviceStorageAddress
          "
        >
          <template slot-scope="scope">
            {{ scope.row.storageAddress }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DevicePersonResponsibleId">
          <template slot-scope="scope">
            {{ scope.row.personResponsibleName }}
          </template>
        </el-table-column>
      </el-table>
      <el-divider class="el-divider-specail" content-position="left"
        ><span>{{ dataList.CalibMethod }}</span>
      </el-divider>
      <el-table
        :data="listDeviceVerification"
        element-loading-text="Loading"
        fit
        highlight-current-row
        height="150px"
      >
        >
        <el-table-column :label="dataList.CalibrationObject">
          <template slot-scope="scope">
            {{ scope.row.verificationObject }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.CalibrationWay">
          <template slot-scope="scope">
            {{ scope.row.verificationWay }}
          </template>
        </el-table-column>
      </el-table>

      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="130px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.CalibRecords }}</span>
        </el-divider>
        <el-form-item
          :label="dataList.CalibrationPersonName"
          :label-width="formLabelWidth"
          prop="calibrationPersonId"
          :error="errorMsg.calibrationPersonId"
        >
          <UserDropDownList
            :value="formData.calibrationPersonId"
            :return-objct.sync="returnObjct"
            @input="borrowPersonChange"
          />
        </el-form-item>
        <el-form-item
          :label="dataList.CalibTime"
          :label-width="formLabelWidth"
          prop="calibrationDate"
          :error="errorMsg.calibrationDate"
        >
          <el-date-picker
            v-model="formData.calibrationDate"
            type="date"
            :placeholder="dataList.SelectDateTime"
            value-format="yyyy-MM-dd"
            @change="calibrationDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          :label="dataList.CertiNumber"
          :label-width="formLabelWidth"
          prop="certificateNo"
          :error="errorMsg.certificateNo"
        >
          <el-input v-model="formData.certificateNo"></el-input>
        </el-form-item>
        <el-form-item
          :label="dataList.CalibFacility"
          :label-width="formLabelWidth"
          prop="company"
          :error="errorMsg.company"
        >
          <el-input v-model="formData.company"></el-input>
        </el-form-item>
        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.ReportCertiCheck }}</span>
        </el-divider>
        <div style="width: 100%">
          <el-table
            :data="reportCertificateTable"
            element-loading-text="Loading"
            fit
            highlight-current-row
          >
            <el-table-column :label="dataList.InspectionItem">
              <template slot-scope="scope">
                {{ scope.row.detectionItem }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.Content">
              <template slot-scope="scope">
                <span v-if="scope.$index == 0 || scope.$index == 1">{{
                  scope.row.content
                }}</span>
                <el-input v-else v-model="scope.row.content"></el-input>
              </template>
            </el-table-column>
            <el-table-column :label="dataList.InspectionResult">
              <template slot-scope="scope">
                <el-radio v-model="scope.row.result" :label="1">{{
                  dataList.Correct
                }}</el-radio>
                <el-radio v-model="scope.row.result" :label="0">{{
                  dataList.Deny
                }}</el-radio>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.CalibResult }}</span>
        </el-divider>

        <el-form-item
          :label="dataList.CalibMethodAndResult"
          :label-width="formLabelWidth"
          prop="content"
          style="width: 100%"
          :error="errorMsg.content"
        >
          <div>
            <TinyEditor v-model="formData.content"></TinyEditor>
          </div>
        </el-form-item>

        <el-form-item
          :label="dataList.DeviceImg"
          prop="imgArray"
          style="width: 100% !important"
        >
          <div class="deviceAddDialogImg">
            <BaseMultipleUpload
              key="BaseUpload"
              ref="BaseUpload"
              v-model="formData.imgArray"
              business-type="110"
              :file-size="5120"
              :limit="3"
              :style-c-s-s="styleCSS"
              :multiple="true"
              :show-file-list="true"
              :list-type="'picture-card'"
              style="
                display: flex;
                align-items: start;
                padding-left: 10px;
                flex-direction: column;
              "
              :tip="dataList.DeviceImgTip()"
              :accept="'.jpeg,.jpg,.png,.gif,.bmp,.tiff'"
            />
          </div>
        </el-form-item>

        <el-form-item
          :label="dataList.DeviceAnnex"
          prop="fileArray"
          style="width: 100% !important"
        >
          <div class="deviceAddDialogFile">
            <BaseUploadFile
              key="BaseUploadFile"
              ref="BaseUploadFile"
              v-model="formData.fileArray"
              business-type="120"
              :file-size="10240"
              :limit="10"
              :multiple="true"
              style="display: flex; align-items: center; padding-left: 10px"
              :tip-text="`${dataList.UploadTypeAs}pdf、doc、docx、xls、xlsx、zip、rar、apk；${dataList.DeviceAnnexTip}`"
            />
          </div>
        </el-form-item>

        <el-form-item
          :label="dataList.Conclusion"
          :label-width="formLabelWidth"
          prop="conclusion"
          :error="errorMsg.conclusion"
        >
          <el-select
            v-model="formData.conclusion"
            :placeholder="dataList.Placeholder"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          style="width: 100%"
          :label="dataList.ConclusionReason"
          :label-width="formLabelWidth"
          prop="conclusionReason"
          :error="errorMsg.conclusionReason"
        >
          <el-input
            v-model="formData.conclusionReason"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="dataList.EquipStatusAfterCalib"
          :label-width="formLabelWidth"
          prop="deviceStatus"
          :error="errorMsg.deviceStatus"
        >
          <DicDropDownList
            v-model="formData.deviceStatus"
            :dict-code="'deviceStatusList'"
            :display-text="displayText"
            :input="dicDropDownClick"
          />
        </el-form-item>
        <el-form-item
          style="width: 100%"
          :label="dataList.NextCalibTime"
          :label-width="formLabelWidth"
          prop="calibrationDateNext"
          :error="errorMsg.calibrationDateNext"
        >
          <el-date-picker
            v-model="formData.calibrationDateNext"
            style="width: 30%; float: left"
            type="date"
            :placeholder="dataList.SelectDateTime"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit(10)">{{
          btn.Save
        }}</el-button>
        <el-button
          type="primary"
          :style="{ width: $i18n.locale === 'en' ? '120px' : '100px' }"
          @click="onSubmit(20)"
          >{{ btn.SaveAndSubmit }}</el-button
        >
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { get, update } from "../../../api/DeviceCalibrationTask";
import UserDropDownList from "../../../components/UserDropDownList.vue";
import DicDropDownList from "../../../components/DicDropDownList.vue";
import {
  conclusion,
  reportCertificateTable,
  normal,
} from "../../../utils/const";
import { getDateByName, formatTime } from "../../../utils/time";
import { mapGetters } from "vuex";
import TinyEditor from "../../../components/TinyEditor.vue";
import { GetStaticImgInfo } from "@/api/Base";

export default {
  name: "DeviceCalibrationTaskDisposeDialog",
  components: { UserDropDownList, DicDropDownList, TinyEditor },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      displayText: [
         this.$t("ModuleDevice.Device.Normal"),
         this.$t("ModuleDevice.Device.Fault"),
      ],
      normal: normal,
      options: conclusion,
      styleCSS: "text-align:left",
      verificationWayList: [],
      returnObjct: true,
      choiceDeviceVisible: false,
      reportCertificateTable: reportCertificateTable,
      list: [],
      listDeviceVerification: [],
      loading: false,
      innerDialogFormVisible: false,
      formLabelWidth: "150px",
      formData: {
        id: 0,
        calibrationPersonId: this.$store.getters.currentUserId,
        calibrationPersonName: this.$store.getters.name,
        calibrationDate: new Date(),
        certificateNo: "",
        company: "",
        content: "",
        imgArray: [],
        fileArray: [],
        sysBusinessImgWarehouseList: [],
        sysBusinessFileWarehouseList: [],
        conclusion: 10,
        calibrationDateNext: null,
        deviceStatus: normal,

        num: "",
        deviceNum: "",
        calibrationPlanNum: "",
        type: 0,
        typeName: "",
        verificationObject: "",
        verificationWay: "",
        planDate: 0,
        status: 0,
        statusName: "",
        remark: "",
        conclusionName: "",
        conclusionReason: "",
        deviceStatusName: "正常",
        projectResultInfo: 0,
        projectResultInfoName: "",
        projectResultRang: 0,
        projectResultRangName: "",
        projectResultSure: 0,
        projectResultSureName: "",
        projectResultPrecise: 0,
        projectResultPreciseName: "",
        projectResultCover: 0,
        projectResultCoverName: "",
        deviceId: 0,
      },
      errorMsg: {
        company: "",
        calibrationPersonId: "",
        calibrationDate: "",
        content: "",
        certificateNo: "",
        imgArray: "",
        fileArray: "",
        conclusion: "",
        calibrationDateNext: "",
        deviceStatus: "",
      },
      formDataRules: {
        company: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        calibrationPersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        calibrationDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        certificateNo: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        conclusion: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        deviceStatus: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {
    dialogFormVisible(val) {
      this.innerDialogFormVisible = val;
    },
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;

    this.init();
  },
  methods: {
    formatTime,
    calibrationDateChange() {
      if (this.formData.type === 10) {
        this.formData.calibrationDateNext = getDateByName(
          this.formData.calibrationDate,
          this.formData.deviceCalibrationPlanInfo.cycle,
          this.formData.deviceCalibrationPlanInfo.cycleName
        );
      } else {
        this.formData.calibrationDateNext = null;
      }
    },
    dicDropDownClick(value, label) {
      this.formData.deviceStatusName = label;
    },
    init() {
      get({ id: this.id }).then((res) => {
        this.formData = res.data;
        if (formatTime(this.formData.calibrationDate) === "") {
          this.formData.calibrationDate = new Date();
        }

        if (formatTime(this.formData.calibrationDateNext) === "") {
          if (this.formData.type === 10) {
            this.formData.calibrationDateNext = getDateByName(
              this.formData.calibrationDate,
              this.formData.deviceCalibrationPlanInfo.cycle,
              this.formData.deviceCalibrationPlanInfo.cycleName
            );
          } else {
            this.formData.calibrationDateNext = null;
          }
        }

        if (this.formData.deviceStatus <= 0) {
          this.formData.deviceStatus = normal;
        }
        this.formData.fileArray = [];
        res.data.sysBusinessFileWarehouseList.map((item) => {
          var obj = item;
          obj.name = item.originalFileName;
          // obj.url = `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${item.filePath}`;
          obj.url = `${item.filePath}`;
          this.formData.fileArray.push(obj);
        });

        this.formData.imgArray = [];
        res.data.sysBusinessImgWarehouseList.map((item) => {
          GetStaticImgInfo(item.filePath).then((res) => {
            item.url = res.data;

            var obj = item;
            obj.name = item.originalFileName;
            // obj.url = `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${item.filePath}`;
            obj.url = res.data;
            obj.imgUrl = item.filePath;
            this.formData.imgArray.push(obj);
          });
        });

        // 判断必填项

        this.reportCertificateTable[0].result = res.data.projectResultInfo;
        this.reportCertificateTable[0].content =
          res.data.projectResultInfoName == null
            ? this.dataList.InfoAs
            : res.data.projectResultInfoName;

        this.reportCertificateTable[1].result = res.data.projectResultRang;
        this.reportCertificateTable[1].content =
          res.data.projectResultRangName == null
            ? this.dataList.WithinScope
            : res.data.projectResultRangName;

        this.reportCertificateTable[2].result = res.data.projectResultSure;
        this.reportCertificateTable[2].content =
          res.data.projectResultSureName == null
            ? res.data.verificationObject
            : res.data.projectResultSureName;

        this.reportCertificateTable[3].result = res.data.projectResultPrecise;
        this.reportCertificateTable[3].content =
          res.data.projectResultPreciseName;

        this.reportCertificateTable[4].result = res.data.projectResultCover;
        this.reportCertificateTable[4].content =
          res.data.projectResultCoverName == null
            ? res.data.verificationWay
            : res.data.projectResultCoverName;

        if (!this.formData.certificateNo) {
          this.formData.conclusion = 10;
        }
        if (!this.formData.certificateNo) {
          this.formData.deviceStatus = this.normal;
          this.formData.deviceStatusName = this.dataList.Normal;
        }

        this.formData.deviceStatus = String(res.data.deviceStatus);
        this.list = res.data.deviceDtos;
        this.listDeviceVerification = [];
        this.listDeviceVerification.push({
          verificationWay: res.data.verificationWay,
          verificationObject: res.data.verificationObject,
        });
        this.formData.calibrationPersonId = this.$store.getters.currentUserId;
      });
    },
    wayInputChange(index, val) {
      this.verificationWayList[index].label = val;
    },
    borrowPersonChange(val) {
      this.formData.calibrationPersonId = val.value;
      this.formData.calibrationPersonName = val.label;
    },
    cancel() {
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit(status) {
      this.formData.status = status;

      this.formData.projectResultInfo = this.reportCertificateTable[0].result;
      this.formData.projectResultInfoName =
        this.reportCertificateTable[0].content;

      this.formData.projectResultRang = this.reportCertificateTable[1].result;
      this.formData.projectResultRangName =
        this.reportCertificateTable[1].content;

      this.formData.projectResultSure = this.reportCertificateTable[2].result;
      this.formData.projectResultSureName =
        this.reportCertificateTable[2].content;

      this.formData.projectResultPrecise =
        this.reportCertificateTable[3].result;
      this.formData.projectResultPreciseName =
        this.reportCertificateTable[3].content;

      this.formData.projectResultCover = this.reportCertificateTable[4].result;
      this.formData.projectResultCoverName =
        this.reportCertificateTable[4].content;

      // 图片
      this.formData.sysBusinessImgWarehouseList = [];
      if (this.formData.imgArray !== undefined) {
        this.formData.imgArray.forEach((item) => {
          var obj = {};
          obj.fileTpyeCode = 1;
          obj.originalFileName = item.originalFileName;
          obj.storageFileName = item.storageFileName;
          obj.filePath = item.filePath;
          this.formData.sysBusinessImgWarehouseList.push(obj);
        });
      }

      // 附件
      this.formData.sysBusinessFileWarehouseList = [];
      if (this.formData.fileArray !== undefined) {
        this.formData.fileArray.forEach((item) => {
          var obj = {};
          obj.fileTpyeCode = 2;
          obj.originalFileName = item.name;
          obj.storageFileName = "";
          obj.filePath = item.url2;
          this.formData.sysBusinessFileWarehouseList.push(obj);
        });
      }

      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          update(this.formData).then((res) => {
            if (res.code === 200) {
              this.$emit("update:id", 0);
              this.closeDialog();
            } else {
              this.showValidateMsgCheck(res);
            }
          });
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("deviceNum", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "verificationPlanNum",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("type", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("typeName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "verificationObject",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("verificationWay", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "verificationMethod",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("planDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("calibrationDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "verificationPersonName",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("content", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("conclusion", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("conclusionName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("conclusionReason", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("deviceStatus", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("deviceStatusName", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
<style scoped lang="scss">
.deviceAddDialogFile {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 150px;
  ::v-deep.base-upload {
    text-align: left;
    display: flex;
    flex-direction: column;
    padding-top: 10px;
    width: 100%;
  }
  ::v-deep .el-upload-list__item {
    width: 50%;
  }
  ::v-deep .el-upload {
    text-align: left;
  }
  ::v-deep .el-upload-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    overflow-y: auto;
  }
  ::v-deep .el-upload__tip {
    color: red;
  }
}
.deviceAddDialogImg {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 150px;
  ::v-deep .el-upload--picture-card {
    width: 116px;
    height: 88px;
    border: 1px solid #dcdfe6;
  }
  ::v-deep .el-upload-list__item {
    width: 116px;
    height: 88px;
    border: 1px solid #dcdfe6;
  }
  ::v-deep.el-upload {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  ::v-deep .tip-text {
    color: red !important;
    font-size: 12px;
  }
  ::v-deep .el-upload-list--picture-card {
    margin-left: 10px;
  }

  ::v-deep .base-upload {
    display: flex;
    flex-direction: row-reverse;
    margin-top: 10px;
  }
}
</style>
